package cn.sunline.rest.util;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.sunline.rest.annotation.Controller;
import cn.sunline.rest.annotation.Req;
import cn.sunline.rest.annotation.Req.Get;

public class ClassTools {

    /**
     * @Description 扫描指定包下面指定注解类
     * @return
     */
    public static List<Class<?>> scanClassWithAnno(String pack,Class<? extends Annotation> AnnoCls){
        List<Class<?>> list = new ArrayList<>();
        try {
            String path = ClassTools.class
                    .getResource("/" + pack.replaceAll("\\.", "/")).toURI().getPath();
            List<File> classFiles = FileTools.getAllClsFilesByPack(path);
            for (File file : classFiles) {
                String className = pack + "." + file.getName().substring(0, file.getName().length() - 6);
                try {
                    Class<?> calss = Class.forName(className);
                    if (calss.getAnnotation(AnnoCls) != null) {
                        list.add(calss);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public static List<Method> scanAnnoMethodByCls(Class<?> cls, Class<? extends Annotation> annoCls){
        List<Method> list = new ArrayList<>();
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();  
            for (Annotation annotation : annotations) {  
                // 获取注解的具体类型  
                Class<? extends Annotation> annotationType = annotation.annotationType();  
                //get 请求
                if (annoCls == annotationType) {
                    list.add(method);
                }
            }
        }
        return list;
    }
    
    public static void main(String[] args) {
        ClassTools.scanClassWithAnno("cn.sunline.rest.util", Controller.class);
    }
}
